<template>
  <Card class="table-body">
    <template #title>
      <div class="title-row pb-">
        <div class="mr-[8px]">
          <span class="text-[16px] mt-[6px] flex-1">
            订单统计
            <el-tooltip
              effect="dark"
              content="默认勾选，系统按下单时间统计“未付款”的订单的销售额与订单数量。 其中由于亚马逊平台不返回“Pending”状态订单的产品金额，系统预估规则是取最近一个同店铺同SKU已付款订单的产品金额"
              placement="top"
            >
              <div class="dk-iconfont icon-Warning ml-[0px]"></div>
            </el-tooltip>
          </span>
          <el-checkbox v-model="formData.pay_status" size="large" class="ml-[8px]" :true-value="-1" :false-value="1">含Pending订单</el-checkbox>
        </div>
        <div class="flex-1 flex">
          <el-tabs v-model="tagShow" @tab-click="tagShowClick" class="mr-[6px] flex-1">
            <el-tab-pane label="事业部销售明细" name="table" />
            <el-tab-pane label="平台销售明细" name="sales" />
          </el-tabs>

          <!-- <div class="tag-show w-[80px]">
            <svg-icon icon-class="table" class="item" :class="tagShow == 'table' ? 'active' : ''" @click="tagShowClick('table')" />
            <svg-icon icon-class="chart" class="item" :class="tagShow == 'chart' ? 'active' : ''" @click="tagShowClick('chart')" />
          </div> -->

          <div class="flex w-[608px]">
            <div>
              <SelectsShopCascade
                v-model:platform="formData.platform_id"
                multiple
                v-model:site="formData.site_id"
                v-model:shop="formData.shop_id"
                :isHandle="true"
                v-if="tagShow == 'table' || tagShow == 'sales'"
              />

              <div class="flex items-center mt-[6px]">
                <!-- <el-radio-group v-model="formData.cycle" class="mr-[12px] w-[136px]" v-if="tagShow == 'chart'">
                  <el-radio-button label="day">日</el-radio-button>
                  <el-radio-button label="week">周</el-radio-button>
                  <el-radio-button label="month">月</el-radio-button>
                </el-radio-group> -->
                <VGroup class="w-[100%]">
                  <Cascader v-model:modelValue="formData.sale_ids" style="width: 200px" placeholder="销售人员" />

                  <el-date-picker
                    v-model="formData.date"
                    type="datetimerange"
                    range-separator="-"
                    start-placeholder="开始时间"
                    end-placeholder="结束时间"
                    style="width: 320px"
                    format="YYYY-MM-DD HH:mm:ss"
                    valueFormat="YYYY-MM-DD HH:mm:ss"
                    :defaultTime="[new Date(2000, 1, 1, 0, 0, 0), new Date(2000, 2, 1, 23, 59, 59)]"
                    v-if="tagShow != 'sales'"
                    :clearable="false"
                    :shortcuts="shortcuts"
                    class="flex-1"
                  />
                </VGroup>
              </div>
            </div>
          </div>
        </div>
      </div>
    </template>
    <!-- <div class="text-right" style="overflow: hidden">
      <div class="my-radio-group" v-if="tagShow == 'chart'">
        <div class="item" :class="formData.key == 'count' ? 'active' : ''" @click="keyChange('count')">订单量</div>
        <div class="item" :class="formData.key == 'price' ? 'active' : ''" @click="keyChange('price')">销售额</div>
      </div>
    </div> -->

    <div class="body-show">
      <!-- <div id="chartDom" v-if="tagShow == 'chart'"></div> -->
      <!-- 平台销售  平台销售明细 -->
      <div style="width: 100%" v-if="tagShow == 'table' || tagShow == 'sales'">
        <VTable ref="tableRef" v-bind="tableOptins" v-if="tabelShow">
          <template #StattableName="{ row }">
            {{ row.name }} 
            <el-tooltip :content="row.tips" placement="top" v-if="row.tips" raw-content>
              <div class="dk-iconfont icon-Warning ml-[4px]"></div>
            </el-tooltip>
          </template>
        </VTable>
      </div>
    </div>
  </Card>
</template>

<script setup lang="jsx">
import Card from "../Card/index.vue"
import SelectsShopCascade from "@/components/Selects/SelectsShopCascade/index.vue"
import Cascader from "@/components/XForm/components/Cascader/index.vue"
import api from "../../api/index.js"

import { shortcuts } from "@/assets/static"

const props = defineProps({})

onMounted(async () => {
  // initEcharts()
  document.addEventListener("fullscreenchange", onFullScreenChange)
  setTimeout(() => {
    showMsg.value = true
  }, 1000)
})

// 监听全屏变化事件
const onFullScreenChange = () => {
  // if (document.fullscreenElement) {
  //   console.log("进入全屏模式")
  // } else {
  //   console.log("退出全屏模式")
  //   // tableRef?.value?.$table.scrollTo(9999)
  // }
  setTimeout(() => {
    tableRef?.value?.$table.scrollTo(9999)
  }, 100)
}

import { formatDate } from "@/utils"
const getTime = () => {
  // const temp = new Date()
  // let date = new Date(temp.setDate(temp.getDate() - 1))
  // temp.setTime(temp.getTime() - 3600 * 1000 * 24 * 6)
  // return [formatDate(new Date(temp.setHours(0, 0, 0, 0))), formatDate(new Date(date).setHours(23, 59, 59, 0))]
  const temp = new Date()
  temp.setTime(temp.getTime() - 3600 * 1000 * 24 * 4)
  return [formatDate(new Date(temp.setHours(0, 0, 0, 0))), formatDate(new Date(new Date().setHours(23, 59, 59, 0)))]
}
// sales table
const tagShow = ref("table")
const formData = ref({
  key: "count",
  date: getTime(), // 时间
  cycle: "day", // 数据维度 年 月 日
  pay_status: -1, // 含Pending订单
})

// 展示类型
const tagShowClick = (e) => {
  nextTick(() => initEcharts())
}

// const salesTableColumn = [
//   { label: "今天", key: "today" },
//   { label: "昨天", key: "yesterday" },
//   // { label: "前天", key: "before_yesterday" },
// ]
const showMsg = ref(false)
const tableRef = ref()
const tabelShow = ref(true)

const echartType = ref("1")
const chartData = ref({})

const initEcharts = async () => {
  if (!formData.value.date) return
  try {
    // 图表
    if (tagShow.value == "chart") {
      // let params = {
      //   start_date: formData.value.date?.[0] || "",
      //   end_date: formData.value.date?.[1] || "",
      //   cycle: formData.value.cycle,
      //   platform_id: platformList.value.map((v) => v.platform_id),
      //   // platform_id: formData.value.platform_id,
      //   stats_method: "histogram",
      //   pay_status: formData.value.pay_status,
      //   sale_ids: formData.value.sale_ids,
      // }
      // const res = await api.homepageStat(params)
      // var chartDom = document.getElementById("chartDom")
      // var myChart = echarts.init(chartDom)
      // let series = []
      // let xAxisData = Object.values(res.data)[0].map((v) => v.date)
      // const emphasisStyle = {
      //   itemStyle: {
      //     shadowBlur: 10,
      //     shadowColor: "rgba(0,0,0,0.3)",
      //   },
      // }
      // platformList.value.forEach((item) => {
      //   let obj = {
      //     name: item.platform_name,
      //     type: "bar",
      //     stack: "one",
      //     emphasis: emphasisStyle,
      //     data: [],
      //   }
      //   obj.data = (res.data[item.platform_id] && res.data[item.platform_id]?.map((v) => v[formData.value.key])) || []
      //   series.push(obj)
      // })
      // // tooltip 总和缓存
      // let zonghe = []
      // let keyLabel = formData.value.key == "count" ? "订单总量" : "销售总额"
      // let bigData = Object.values(res.data)
      // zonghe = bigData[0].map((item, i) => eval(bigData.map((v) => v[i]?.[formData.value.key] || 0).join("+")).toFixed(2))
      // var option
      // option = {
      //   legend: {
      //     data: platformList.value.map((v) => v.platform_name), // 站点名称
      //     left: "0",
      //   },
      //   // 自定义tooltip内容
      //   tooltip: {
      //     formatter: (item) => {
      //       return `<div>
      //       <div>${item.name}</div>
      //       <div>${keyLabel}：${zonghe[item.dataIndex]} ${formData.value.key != "count" ? "CNY" : ""}</div>
      //       <div>${item.seriesName}： ${item.value} ${formData.value.key != "count" ? "CNY" : ""}</div>
      //     </div>`
      //     },
      //   },
      //   xAxis: {
      //     data: xAxisData,
      //     name: "X Axis",
      //     // axisLine: { onZero: true },
      //     splitLine: { show: false },
      //     splitArea: { show: false },
      //   },
      //   yAxis: {
      //     splitLine: {
      //       lineStyle: {
      //         type: "dashed",
      //       },
      //     },
      //   },
      //   grid: {
      //     left: "0%",
      //     right: "0",
      //     bottom: "100px",
      //     containLabel: true,
      //   },
      //   series,
      // }
      // option && myChart.setOption(option)
    } else {
      // 表格
      let params = {
        start_date: formData.value.date?.[0] || "",
        end_date: formData.value.date?.[1] || "",
        cycle: "day",
        stats_method: "sheet",
        pay_status: formData.value.pay_status,
        sale_ids: formData.value.sale_ids,
        platform_id: formData.value.platform_id,
        site_id: formData.value.site_id,
        shop_id: formData.value.shop_id,
      }

      // 事业部销售明细
      if (tagShow.value == "table") {
        // 事业部销售明细
        getHomepageStat(params)
      } else {
        // 平台销售明细

        getPlatformSales(params)
      }
    }
  } catch (err) {
    console.warn(err)
  }
}

const tableTip = {
  销售额: `按下单时间筛选，不包含正常取消订单（合并/拆分的原订单正常统计），统计订单的产品金额，各平台规则不同，统计的金额是否含税各不相同：
            <br/>亚马逊与其他平台：欧洲各站点和日本站点产品金额是含税，美国站和澳洲站产品金额是不含税
            <br/>ebay与各半托管平台：各站点产品金额不含税`,
  订单量: `按下单时间筛选，不包含取消订单（合并/拆分的原订单正常统计），按平台订单号统计订单数量，不统计重复的拆分订单`,
  客单价: `按下单时间筛选，客单价 = 销售额 / 订单量`,
}

// 事业部销售明细
const getHomepageStat = async (params) => {
  console.log("事业部销售明细")
  const res = await api.homepageStat(params)
  if (!res.data.length) {
    tableRef?.value?.$table.loadData([])
    return
  }
  let columnsKeys = Object.keys(res.data[0]).filter((v) => !"data,汇总,name".includes(v))
  let tableColumns = columnsKeys.map((v) => ({
    field: v,
    title: v,
    minWidth: "150px",
    align: "center",
    slots: {
      default: ({ row }) => (
        <div>
          <span> {row?.[v]}</span>
          {row?.[`${v}-1`] ? <span> ({row?.[`${v}-1`]}%)</span> : ""}
        </div>
      ),
    },
  }))

  tableColumns.unshift({
    field: "name",
    title: "",
    minWidth: "200px",
    params: "left",
    treeNode: true,
    slots: {
      header: () => {
        return (
          <div class="ml-[10px]  flex items-center mt-[2px]  cursor-pointer" onClick={() => onPlatformSalesArrow()}>
            <el-link type="primary" underline={false}>
              <span class="text-[12px]"> {platformSalesArrow.value ? "展开" : "收起"}</span>
              <svg-icon icon-class="arrow_down" class={`w-[14px]] h-[14px]  ${platformSalesArrow.value ? "rotate-[0deg]" : "rotate-[180deg]"}`} />
            </el-link>
          </div>
        )
      },
      default: ({ row }) => {
        return (
          <div>
            {row.name}
            {"销售额,订单量,客单价".includes(row.name) ? (
              <el-tooltip effect="dark" content={tableTip[row.name]} placement="top" raw-content>
                <div class="dk-iconfont icon-Warning ml-[4px]"></div>
              </el-tooltip>
            ) : (
              ""
            )}
          </div>
        )
      },
    },
  })
  tableColumns.push({
    field: "汇总",
    title: "汇总",
    width: "150px",
    params: "right",
    align: "center",
    slots: {
      header: () => (
        <div>
          汇总
          <el-tooltip effect="dark" content="1，默认查询近5天（包含今天）的数据<br/>2，可手动选择时间查询条件，系统会根据查询结果汇总统计销售额/订单量/客单价" placement="top" raw-content>
            <div class="dk-iconfont icon-Warning ml-[4px]"></div>
          </el-tooltip>
        </div>
      ),
      default: ({ row }) => (
        <div class="text-center">
          <span> {row?.["汇总"]}</span>
          {row?.[`汇总-1`] ? <span> ({row?.[`汇总-1`]}%)</span> : ""}
        </div>
      ),
    },
  })

  let order = ["数字化中心", "家居事业部", "汽配事业部", "清洁&护理事业部", "环境电子新单元", "环境电子事业处"]
  console.log(11111)

  res.data.forEach((item) => {
    // item.data = item.data.sort((a, b) => b["汇总"] - a["汇总"])
    item.data = item.data.sort((a, b) => {
      return order.indexOf(b.name) - order.indexOf(a.name)
    })

    item.data.forEach((items) => {
      if (item.name == "客单价") return
      for (const key in items) {
        if (!"name".includes(key)) {
          items[`${key}-1`] = ((items[key] / item[key]) * 100 || 0).toFixed(2)
        }
      }
    })
  })

  setTimeout(() => {
    tableRef?.value?.$table.loadData(res.data)
    tableRef?.value?.$table.loadColumn(tableColumns)
    tableRef?.value?.$table.setAllTreeExpand(1)

    setTimeout(() => {
      tableRef?.value.updateScroll()
      tableRef?.value?.$table.scrollTo(9999)
      nextTick(() => {
        tableRef?.value.updateScroll()
      })
    }, 300)
  }, 10)
}

// 平台销售明细
const getPlatformSales = (params) => {
  console.log("平台销售明细111")
  api.platformSalesDetails(params).then((res) => {
    // console.log(res)
    let dateKeys = ["today", "yesterday", "before_yesterday"]
    res.data.forEach((item) => {
      item.platform.forEach((v) => {
        v.name = v.platform

        dateKeys.forEach((k) => {
          v[k].sales_amount = Number(v[k].sales_amount) || 0
          v[k].sales_quantity = Number(v[k].sales_quantity) || 0
          v[k].customer_price = Number(v[k].customer_price) || 0
        })
      })
      item.data = item.platform

      dateKeys.forEach((k) => {
        item[k].sales_amount = Number(item[k].sales_amount) || 0
        item[k].sales_quantity = Number(item[k].sales_quantity) || 0
        item[k].customer_price = Number(item[k].customer_price) || 0
      })
    })

    tabelShow.value = false

    nextTick(() => {
      tabelShow.value = true
      setTimeout(() => {
        tableRef?.value?.$table.loadColumn(salesTableColumns)

        tableRef?.value?.$table.loadData(res.data)
        tableRef?.value?.$table.setAllTreeExpand(1)
        setTimeout(() => {
          tableRef?.value?.$table.scrollTo(9999)
        }, 100)
      }, 100)
    })
  })
}
// 平台销售明细 展开收起
const platformSalesArrow = ref(false)
const onPlatformSalesArrow = () => {
  tableRef?.value.updateScroll()
  platformSalesArrow.value = !platformSalesArrow.value
  if (platformSalesArrow.value) {
    tableRef?.value?.$table.setAllTreeExpand(0)
  } else {
    tableRef?.value?.$table.setAllTreeExpand(1)
  }
}

// 列表配置
const tableOptins = reactive({
  formConfig: {},
  height: "auto",
  border: "full",
  showOverflow: true,
  sortConfig: {
    remote: false,
    defaultSort: {
      field: "yesterday.sales_amount",
      order: "desc",
    },
    sortMethod: ({ data, sortList }) => {
      let order = sortList[0].order
      let fields = sortList[0].field.split(".")
      data.forEach((item) => {
        item.data = item.data.sort((a, b) => {
          return order == "asc" ? a[fields[0]]?.[fields[1]] - b[fields[0]]?.[fields[1]] : b[fields[0]]?.[fields[1]] - a[fields[0]]?.[fields[1]]
        })
      })
      return data
    },
  },

  columns: [],
  data: [],
  proxyConfig: { enabled: false },
  treeConfig: {
    rowField: "name",
    childrenField: "data",
    trigger: "row",
    toggleMethod: ({ row }) => {
      tableRef?.value.updateScroll()
      return true
    },
  },
})

const salesTableColumns = [
  {
    field: "name",
    title: "销售平台",
    params: "left",
    width: "200px",
    treeNode: true,
    slots: {
      header: () => (
        <div class="flex items-center">
          销售平台
          <div class="ml-[8px]  flex items-center mt-[2px]  cursor-pointer" onClick={() => onPlatformSalesArrow()}>
            <el-link type="primary" underline={false}>
              <span class="text-[12px]"> {platformSalesArrow.value ? "展开" : "收起"}</span>
              <svg-icon icon-class="arrow_down" class={`w-[14px]] h-[14px]  ${platformSalesArrow.value ? "rotate-[0deg]" : "rotate-[180deg]"}`} />
            </el-link>
          </div>
        </div>
      ),
    },
  },

  {
    field: "before_yesterday",
    title: "前天",
    align: "center",
    children: [
      {
        field: "before_yesterday.sales_quantity",
        title: "销售订单数",
        width: "140px",
        sortable: true,
        align: "center",
        slots: {
          default: ({ row }) => (
            <div>
              {row?.before_yesterday?.sales_quantity}

              {/* <div class="text-[12px]">({row?.before_yesterday?.sales_quantity_ratio}%)</div> */}
              {row.platform_id ? <span>({row?.before_yesterday?.sales_quantity_ratio}%)</span> : ""}
            </div>
          ),
        },
      },
      {
        field: "before_yesterday.sales_amount",
        title: "销售额($)",
        width: "140px",
        sortable: true,
        align: "center",
        slots: {
          default: ({ row }) => (
            <div>
              {row?.before_yesterday?.sales_amount}
              {/* <div class="text-[12px]">({row?.before_yesterday?.sales_amount_ratio}%)</div> */}
              {row.platform_id ? <span>({row?.before_yesterday?.sales_amount_ratio}%)</span> : ""}
            </div>
          ),
        },
      },
      { field: "before_yesterday.customer_price", title: "客单价($)", width: "120px", sortable: true, align: "center" },
    ],
  },

  {
    field: "yesterday",
    title: "昨天",
    align: "center",
    children: [
      {
        field: "yesterday.sales_quantity",
        title: "销售订单数",
        width: "140px",
        sortable: true,
        align: "center",
        slots: {
          default: ({ row }) => (
            <div>
              {row?.yesterday?.sales_quantity}
              {/* <div class="text-[12px]">({row?.yesterday?.sales_quantity_ratio}%)</div> */}
              {row.platform_id ? <span>({row?.yesterday?.sales_quantity_ratio}%)</span> : ""}
            </div>
          ),
        },
      },
      {
        field: "yesterday.sales_amount",
        title: "销售额($)",
        width: "140px",
        sortable: true,
        align: "center",
        slots: {
          default: ({ row }) => (
            <div>
              {row?.yesterday?.sales_amount}
              {/* <div class="text-[12px]">({row?.yesterday?.sales_amount_ratio}%)</div> */}
              {row.platform_id ? <span>({row?.yesterday?.sales_amount_ratio}%)</span> : ""}
            </div>
          ),
        },
      },
      { field: "yesterday.customer_price", title: "客单价($)", width: "120px", sortable: true, align: "center" },
    ],
  },

  {
    field: "today",
    title: "今天",
    align: "center",
    children: [
      {
        field: "today.sales_quantity",
        title: "销售订单数",
        width: "140px",
        align: "center",
        sortable: true,
        slots: {
          default: ({ row }) => (
            <div>
              {row?.today?.sales_quantity}
              {/* ({row?.today?.sales_quantity_ratio}%) */}
              {row.platform_id ? <span>({row?.today?.sales_quantity_ratio}%)</span> : ""}
            </div>
          ),
        },
      },
      {
        field: "today.sales_amount",
        title: "销售额($)",
        width: "140px",
        sortable: true,
        align: "center",
        slots: {
          default: ({ row }) => (
            <div>
              {row?.today?.sales_amount}
              {/* ({row?.today?.sales_amount_ratio}%) */}
              {row.platform_id ? <span>({row?.today?.sales_amount_ratio}%)</span> : ""}
            </div>
          ),
        },
      },
      { field: "today.customer_price", title: "客单价($)", width: "120px", sortable: true, align: "center" },
    ],
  },
]
// const getData = () => {
//   console.log("getData")

//   initEcharts()
// }
watch(
  formData.value,
  (value) => {
    initEcharts()
  },
  { immediate: true, deep: true }
)
</script>
<style lang="scss" scoped>
.table-body {
  flex-direction: column;
  height: calc(100vh - 260px);
  display: flex;
  :deep(.row--level-0) {
    background-color: var(--base-small-bg-color);
    .cell--fixed {
      background-color: var(--base-small-bg-color);
    }
  }
  :deep(.title) {
    padding-bottom: 0 !important;
  }
  .body-show {
    height: 100%;
    > div {
      height: 100%;
    }
    :deep(.vxe-pager--wrapper) {
      display: none;
    }
  }
  .title-row {
    width: 100%;
    display: flex;
    position: relative;
    .tag-show {
      .item {
        width: 32px;
        height: 32px;
        padding: 10px;
        border: 1px solid #e6e7e9;
        border-radius: 4px;
        display: inline-block;
        margin-right: 8px;
        color: #e6e7e9;
      }
      .item.active {
        background: #3487ff;
        border-color: #3487ff;
        color: #fff;
      }
    }
  }
}

#chartDom {
  width: 100%;
  height: 100%;
}
:deep(.el-tabs__item) {
  padding: 0 6px;
}
// .my-radio-group {
//   background: #fafafa;
//   display: flex;
//   border-radius: 16px;
//   padding: 3px;
//   float: right;
//   z-index: 999;
//   .item {
//     width: 65px;
//     height: 26px;
//     line-height: 26px;
//     text-align: center;
//     border-radius: 13px;
//     opacity: 0.87;
//   }
//   .item.active {
//     background: #eaf3ff;
//     opacity: 0.87;
//     color: #3487ff;
//   }
// }

// :deep(.el-tabs__nav-wrap::after) {
//   display: none;
// }
</style>
